package com.tfswue.lsh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfswue.lsh.entity.User;
import com.tfswue.lsh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api/users")
public class RestFulUserController {
    @Autowired
    private UserService userService;
    //查询所有用户

    @GetMapping
    public List<User> getAllUsers(){
        return userService.list();
    }
    //查询指定用户

    @Cacheable(value = "dataCache",key = "#id")
    @GetMapping("/{id}/{name}")
    public User getUserById( @PathVariable("id") Integer id,@PathVariable("name") String name){
        log.error("id: {} , name: {},id,name");
        return userService.getById(id);
    }
    //分页查询
    @GetMapping("/querypage/{page}/{size}")
    public List<User> queryPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Page<User> testpage= new Page<>(1,size);
       Page<User> userPage = userService.page(testpage,null);
       return userPage.getRecords();
    }
    @GetMapping("/querylist/{page}/{size}")
    public List<User> queryList(@PathVariable("page") Integer page,
                                @PathVariable("size") Integer size,
                                @RequestBody User user){
        QueryWrapper<User> queryWrapper= new QueryWrapper<>();
        if (user.getUsername() !=null){
            queryWrapper.like("username",user.getUsername());
        }
        if (user.getEmail() !=null){
            queryWrapper.like("email",user.getEmail());
        }

        Page<User> testpage= new Page<>(page,size);
        Page<User> userPage = userService.page(testpage,queryWrapper);
        return userPage.getRecords();
    }
    //添加用户
    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }

    //修改用户
    @CachePut(value = "dataCache",key = "#id")
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

//删除数据
@CacheEvict(value = "dataCache",key = "#id")
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable("id") Integer id) {
        return userService.removeById(id);
    }


}
